package com.ajavaer.framework.job.jobs;

import com.ajavaer.framework.job.type.JobType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StopWatch;

public abstract class BaseJob {
    Logger log = LoggerFactory.getLogger(BaseJob.class);
    JobType jobType;

    public BaseJob(JobType jobType) {
        this.jobType = jobType;
    }

    public void process() {
        StopWatch stopWatch = new StopWatch();

        log.info("job [{}] running", this.jobType.name());
        boolean succ = false;
        try {
            stopWatch.start();
            init();
            boolean flag = runJob();
            if (flag) {
                success();
                succ = true;
            } else {
                error(null);
            }
        } catch (Exception e) {
            error(e);
        } finally {
            complate();
            stopWatch.stop();
        }
        log.info("job [{}] complate,succ:{},timecost:{} seconds", this.jobType.name(), succ, stopWatch.getTotalTimeSeconds());
    }

    public void init() {
    }

    /**
     * 调度
     */
    public abstract void dispatch();

    /**
     * 执行
     *
     * @return
     */
    public abstract boolean runJob();

    /**
     * 完成(无论成功与否都会调用)
     *
     * @return
     */
    public void complate() {
    }

    /**
     * 成功
     *
     * @return
     */
    public void success() {
    }

    /**
     * 错误
     *
     * @return
     */
    public void error(Exception e) {
        if (e != null) {
            log.error(e.getMessage(), e);
        }
    }

    public JobType getJobType() {
        return jobType;
    }

    public void setJobType(JobType jobType) {
        this.jobType = jobType;
    }
}
